// pages/cart/recommend_list/recommend_list.js
const app = getApp();
const setting = app.globalData.setting;
const request = app.request;
import LoadMore from '../../../utils/LoadMore.js';
const load = new LoadMore;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBar: app.globalData.statusBar,
    title: "",
    headerText: "",
    recommend: [], //推荐商品
    currentPage: 1,
    userInfo: app.globalData.userInfo,
    url: setting.url,
    isTriggered: false,
    type: 1, // 1为推荐，2为人气，3为新品
    indexnum: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    load.init(this, '', 'recommend');
    var title = "", txt = "";
    switch (options.type) {
      case "1":
        title = "甄选推荐";
        txt = "甄选";
        break;
      case "2":
        title = "人气产品";
        txt = "人气";
        break;
      default:
        title = "新品推荐";
        txt = "新品";
        break;
    }
    this.setData({
      title: title,
      headerText: txt,
      type: options.type
    })
    this.requestRecommend();
  },

  // 下拉刷新
	onRefresherrefresh() {
		this.setData({
			isTriggered: true
		})
		this.data.recommend = [];
		this.data.currentPage = 1;
		this.requestRecommend();
	},

  // 触底刷新
	onScrolltolower() {
		this.data.currentPage++
		this.requestRecommend('more')
	},

  // 商品列表
	requestRecommend: function (type) {
		let that = this;
    let requestUrl = '';
    switch (this.data.type) {
      case "1":
        requestUrl = '/api/index/recommend?p=' + that.data.currentPage;
        break;
      case "2":
        requestUrl = '/api/index/getHotGood?page=' + that.data.currentPage;
        break;
      default:
        requestUrl = '/api/index/getNewGoods?page=' + that.data.currentPage;
        break;
    }
		load.request(requestUrl, function (res) {
      wx.stopPullDownRefresh();
			if (type == 'more') {
        let result = res.data.result || [];
        if(result.length == 0) {
          that.data.currentPage--;
        }
				that.setData({
					recommend: [...that.data.recommend, ...result]
        })
			}
		}, () => { }, () => {
      this.setData({
        isTriggered: false
      })
		});
  },

  clickMenu(e) {
		let that = this;
		//在个人中心浏览其他入口页面前判断是否登录
		if (!that.data.userInfo) {
			app.getUserInfo(function (userInfo) {
				that.setData({
					userInfo: userInfo,
					click: false
				});
			}, true, false);
			return false;
		}
		wx.navigateTo({
			url: e.currentTarget.dataset.url
		});
  },

  addNum: function (e) {
		let that = this;
		//在个人中心浏览其他入口页面前判断是否登录
		if (!that.data.userInfo) {
			app.getUserInfo(function (userInfo) {
				that.setData({
					userInfo: userInfo,
					click: false
				});
			}, true, false);
			return false;
		}
		let index = e.currentTarget.dataset.item
		let cart = that.data.recommend[index];
		let data = {
			goods_id: cart.goods_id,
			goods_num: 1,
			item_id: 0
		}
		request.post('/api/cart/add', {
      data: data,
      isShowLoading:false,
			success: function (res) {
				if (res.data.status == 1) {
					cart.cart_num++;
					that.setData({
						['recommend[' + index + '].cart_num']: cart.cart_num,
						// ['recommend[' + index + '].cart_id']: res.data.cart_id
          });
          app.showTextWarining('加入购物车成功');
					// 更新购物车角标数量
					that.getCardList(index);
				}
			}
		})
	},

	subNum(e) {
		let that = this;
		//在个人中心浏览其他入口页面前判断是否登录
		if (!that.data.userInfo) {
			app.getUserInfo(function (userInfo) {
				that.setData({
					userInfo: userInfo,
					click: false
				});
			}, true, false);
			return false;
		}
		let index = e.currentTarget.dataset.item
		let cart = this.data.recommend[index]
		let data = {
			'cart[id]': cart.cart_id,
			'cart[goods_num]': cart.cart_num - 1,
      type: 1
		}
		request.post(that.data.url + '/api/cart/changeNum', {
      data: data,
      isShowLoading:false,
			success: function (res) {
				if (res.data.status == 1) {
					that.setData({
						['recommend[' + index + '].cart_num']: cart.cart_num - 1
					});
					// 更新购物车角标数量
					that.getCardList();
				}
			}
		});
  },
  getCardList: function (idx) {
		let that = this;
		request.get(that.data.url + '/api/cart/index?type=1', {
      isShowLoading:false,
			success: function (res) {
				that.setData({
					indexnum: res.data.result.user_cart_goods_type_num
        })
        if(idx || idx == 0) {
          for (let index = 0; index < res.data.result.cart_list.length; index++) {
            const element = res.data.result.cart_list[index];
            if(element.goods_id == that.data.recommend[idx].goods_id) {
              that.setData({
                ['recommend[' + idx + '].cart_id']: element.id
              });
              return;
            }
          }
        }
			}
		});
  },
  
  // 返回上一页
  back() {
    wx.navigateBack();
  }
})